﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using ActionSystem.Core.Ranges;
using ActionSystem.Core.Utils;

namespace ActionSystem.Core.HitLogic
{
    public abstract class BaseRangeBoxItem : MonoBehaviour, IPoolItem
    {
        protected IItem value;
        protected int layermask;
        public bool IsDeleted { get; set; }
        public static BaseRangeBoxItem GetRangeBoxItem<T>() where T : BaseRangeBoxItem
        {
            return GameObjectPool<T>.Create();
        }
        /// <summary>
        /// 删除
        /// </summary>
        public void PoolItemDelete()
        {            
            if(gameObject.transform.root.gameObject.activeSelf)//判断父物体是否是被系统销毁,避免销毁时设置parent = null;
            {
                this.transform.parent = null;
                this.transform.position = Vector3.down * 10000;
                this.transform.rotation = Quaternion.identity;
                this.value = null;
                layermask = 0;
                PutBackToPool();
            }else
            {
                //Debug.Log("父物体被系统销毁");
                //Don't set transform.parent=null inside OnDestroy(),有这个问题，这里就不放回池子了,让内存销毁好了
            }

        }   
        /// <summary>
        /// 放回对象池
        /// </summary>        
        protected abstract void PutBackToPool();
        /// <summary>
        /// 重置PoolItem       
        /// </summary>
        public abstract void PoolItemReset();


        /// <summary>
        /// 设置形状参数
        /// </summary>
        /// <param name="item">当前参数，用于cast</param>
        public virtual void SetRangeShape(IItem item)
        {
            this.value = item;
        }

        

        /// <summary>
        /// 添加到Slot上，只有第一次生效
        /// </summary>
        /// <param name="slot">位置</param>
        public void AttachToSlotTransfrom(Transform slot)
        {
            if(slot==null)
            {
                return;
            }
            if(transform.parent!=null)
            {
                return;
            }
            transform.rotation *= slot.rotation;
            transform.position = slot.localToWorldMatrix*new Vector4(transform.position.x, transform.position.y, transform.position.z,1);            
            transform.parent = slot;                        
        }
        /// <summary>
        /// 碰撞检测
        /// </summary>
        /// <param name="slot">位置</param>
        /// <param name="item">数据</param>
        /// <param name="unityLayerMask">mask</param>
        /// <returns>碰撞的个数</returns>
        public abstract int HitDetect(int unityLayerMask);
        public int HitDetect()
        {
            return HitDetect(this.layermask);
        }
        public void SetLayer(int unityLayer,int unityLayerMask)
        {
            this.gameObject.layer = unityLayer;
            this.layermask = unityLayerMask;
        }
    }
}

